/**
 * @name 请求方法
 * @param {String} path 接口地址
 * @param {Object} params 请求参数
 * @param {String} method 请求方法
 * @param {Boolean} loading 是否显示加载中提示
 * @returns {Promise} Promise对象
 */
const http = (path, params = {}, method = "POST", loading = false) => {
  const baseUrl = import.meta.env.VITE_APP_BASE_URL;
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + path,
      method,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      timeout: 60000,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

const Get = (path, params = {}, loading = false) => {
  return http(path, params, "GET", loading);
};

const Post = (path, params = {}, loading = false) => {
  return http(path, params, "POST", loading);
};

/**
 * @name 上传文件
 * @param {String} type 上传文件类型，默认为image
 * @param {Boolean} multiple 是否多选，默认为false
 */
const UploadFiles = (type = "image", multiple = false) => {
  return new Promise(async (resolve, reject) => {
    const files = await uni.chooseImage({
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      count: multiple ? 9 : 1,
    });
    uni.uploadFile({
      url: import.meta.env.VITE_APP_BASE_URL + "upload",
      name: "file",
      files: files.tempFilePaths,
      success: (res) => {
        console.log(res);
        if (res.statusCode === 200) {
          resolve(JSON.parse(res.data));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};
export { Get, Post, UploadFiles };
